<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
    <el-form
      ref="formRefs"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="180px"
    >
      <el-form-item label="cs平台" prop="csPlatformId">
        <el-select
          v-model="formData.csPlatformId"
          clearable
          filterable
          placeholder="请选择cs平台"
          @change="platChange($event)"
        >
          <el-option
            v-for="item in packageList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="SystemTenantForm" setup>
import * as TenantApi from '@/api/system/tenant'

const { t } = useI18n() // 国际化
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  csPlatformId: undefined,
  name: undefined
})
const formRules = reactive({
  csPlatformId: [{ required: true, message: 'cs平台不能为空', trigger: 'blur' }]
})
const formRefs = ref() // 表单 Ref
const packageList = ref([]) // 平台列表

/** 打开弹窗 */
const opens = async (params) => {
  dialogVisible.value = true
  dialogTitle.value = t('CS平台选择')
  formType.value = 'CS平台选择'
  resetForm()
  packageList.value = await TenantApi.getPlatform(params) //接口待改 ,新接口需要携带参数用户名与密码
}
defineExpose({ opens }) // 提供 open 方法，用于打开弹窗

/** 选择平台变化 */
const platChange = (e: any) => {
  const data = packageList.value.find(function (item) {
    return item.id === e
  })
  formData.value.name = data.name
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRefs) return
  const valid = await formRefs.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success', formData.value)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    csPlatformId: undefined,
    name: undefined
  }
  formRefs.value?.resetFields()
}
</script>
